package com.syxbyi.hmwk2;

import java.util.Objects;
import java.util.Random;

/**
 * 定义一个长度为[16][16]的整型二维数组并输入或指定所有位置的元素值
 * 1 实现二维数组中所有行和所有列中所有元素的累加和并打印。
 *
 * 2 分别实现二维数组中左上角到右下角和右上角到左下角所有元素的累加和并打印。
 */
public class PrintSum {
    private int[][] matrix;
    private int row;
    private int col;

    public PrintSum(int[][] m) {
        // input check
        row = m.length;
        if (row <= 0) {
            defaultMatrix();
            return;
        }
        col = m[0].length;
        if (col != row) {
            defaultMatrix();
            return;
        }
        for (int i = 1; i < row; i++) {
            if (col != m[i].length) {
                defaultMatrix();
                return;
            }
        }
        matrix = m;
    }

    public int getRowSum(int index) {
        Objects.checkIndex(index, row);
        int s = 0;
        for (int j = 0; j < col; j++) {
            s += matrix[index][j];
        }
        return s;
    }

    public int getColSum(int index) {
        Objects.checkIndex(index, col);
        int s = 0;
        for (int i = 0; i < row; i++) {
            s += matrix[i][index];
        }
        return s;
    }

    public int getMainDiagonalSum() {
        int s = 0;
        for (int i = 0; i < row; i++) {
            s += matrix[i][i];
        }
        return s;
    }

    public int getAntiDiagonalSum() {
        int s = 0;
        for (int i = 0; i < row; i++) {
            s += matrix[i][row - i - 1];
        }
        return s;
    }

    private void defaultMatrix() {
        System.out.println("Input matrix is invalid");
        row = 16;
        col = 16;
        matrix = new int[row][col];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                matrix[i][j] = i + j;
            }
        }
        System.out.println("Default matrix is:");
        print();
    }

    public void print() {
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                System.out.printf("%d%s ", matrix[i][j], matrix[i][j]>=10 ? " " : "  ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        Random random = new Random(1);
        final int row = 16;
        final int col = 16;
        int[][] m = new int[row][col];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
//                m[i][j] = random.nextInt(100);
                m[i][j] = i + j;
            }
        }
        PrintSum t = new PrintSum(m);
        t.print();
        System.out.printf("row %d sum: %d\n", 0, t.getRowSum(0));
        System.out.printf("col %d sum: %d\n", 0, t.getColSum(0));
        System.out.printf("main diagonal sum: %d\n", t.getMainDiagonalSum());
        System.out.printf("anti diagonal sum: %d\n", t.getAntiDiagonalSum());
    }
}
